//https://blog.csdn.net/weixin_42289080/article/details/130725695
import {defineStore} from 'pinia'
import userUser  from "./userUser.js";
import commonLang from "../language/lang/common/commonLang";
import {I18Parse} from '@lowcode/jpaas-base-lib';
import {USE_MAIN} from "./fixedValue";
import ResourceApi from "@/common/api/user/resource";
//mapStores  mapState  mapActions
//storeToRefs  $patch
//参数一：容器id必须唯一;
export default defineStore('main', {
    state: () => {//必须是箭头函数
        return {
            logined:false,//登录状态
            hideArea:false,//隐藏头部与左侧区域
            menus:[], //菜单
            routers:[], //动态获取的路由
            curApp:{},//当前的应用对象
            appKey:"", //当前应用标识
            navigations:[], //保存页签
            navigation:"appHome", //当前选中的页签key
            selectedMenuKey:"", //左侧菜单选择的key
            openMenuKeys:[], //当前左侧展开的菜单
            selectTopMenuKey:"appHome",//当前头部菜单选择的key
            openTopMenuKeys:[],
            buttons: {},//有权限的按钮
            allButtons: {},//所有的按钮
            microApp:[],//微前端路径
            hasBack:false,//是否有进入后台的权限
            /* 新版全部应用里面的应用选中 存储的是appId */
            appSelectId:'',
            //存储应用的左侧菜单，{[appId]:menus}
            cacheLeftMenus:{},
            // 是否有主页
            haveHomePage:false,
            //当前点击的内置应用
            sysApp:{},
            //当前上下文的应用
            currentApps:[],
        }
    },
    //类似组件的computed,有缓存的功能
    getters: {
        getAppKey() {
            return this.appKey;
        },
        isNavActive(){
            return this.navigations.some(item=>item.menuKey === this.navigation)
        }
    },
    //类似组件的methods  封装业务逻辑  修改state
    actions: {
        setCacheLeftMenus({appId,menus}){
            this.cacheLeftMenus[appId] = menus;
        },
        setAppSelectId(key){
            this.appSelectId = key ;
        },
        setLogined(logined) {
            this.logined = logined;
        },
        setHideArea(hideArea) {
            this.hideArea = hideArea;
        },
        setMenus(menus) {
            this.menus = menus;
        },
        setRouters( routers){
            this.routers = routers;
        },
        setAppKey(appKey){
            this.appKey = appKey;
        },
        setCurApp(app){
            this.curApp = app;

        },
        setHaveHomePage(have){
            this.haveHomePage = have;
        },
        setSysApp(app){
            this.sysApp = app;
            //查找应用是否存在，如果存在则更新，否则添加
            const index = this.currentApps.findIndex(item => item.appId === app.appId);
            if (index !== -1) {
                // 如果找到，更新对象
                this.currentApps[index] = app;
            } else {
                // 如果没有找到，添加新对象
                this.currentApps.push(app);
            }
        },
        getCurAppName(){
            let title="";
            let language= window.localStorage.getItem('language') || 'zh-CN'
            if(this.curApp && this.curApp.name ){
                if(typeof this.curApp.name === 'string'){
                    let name = new Function(`return ${this.curApp.name}`)()
                    title= name[language]
                } else {
                    title =this.curApp.name[language];
                }
            }
            title= title || I18Parse.getI18Val(commonLang.homeTitle, "homeTitle", "敏捷开发平台");
            return title;
        },
        setNavigations(navigations){
            this.navigations = navigations;
        },
        setNavigation(navigation){
            this.navigation = navigation;
        },
        setSelectedMenuKey(selectedMenuKey){
            this.selectedMenuKey = selectedMenuKey;
        },
        setSelectTopMenuKey(selectedTopMenuKey){
            this.selectTopMenuKey = selectedTopMenuKey;
        },
        setOpenMenuKeys(openMenuKeys){
            this.openMenuKeys = openMenuKeys;
        },
        setOpenTopMenuKeys(openTopMenuKeys){
            this.openTopMenuKeys = openTopMenuKeys;
        },
        /**
         * 用户有权限的菜单.
         * {
         *     appAlias:['key1','key2']
         * }
         * @param buttons
         */
        setButtons(btns){
            if(!this.buttons){
                this.buttons =  {};
            }
            this.buttons = Object.assign(this.buttons,btns)
        },
        /**
         * 应用所有的配置的按钮.
         * @param allButtons
         */
        setAllButtons(btns){
            if(!this.allButtons){
                this.allButtons =  {};
            }
            this.allButtons = Object.assign(this.allButtons,btns)
        },
        setMicroApp(microApp){
            this.microApp = microApp;
        },
        _getHomeIndex(obj){
            /*设置应用首页菜单*/
            let lan = window.localStorage.getItem('language');
            let parentTitle = new Function (`return ${obj.title}`)()
            let title = JSON.stringify({'zh-CN':`${parentTitle[lan]}-首页`, 'en-US':'Home Index'})
            let key = `homeIndex_${obj.key}`
            return {
                menuKey:key,
                key,
                icon:JSON.stringify({"type":"vue3-jpaas-line","icon":"icon-linegongzuotai"}),
                iconPC:JSON.stringify({"type":"vue3-jpaas-line","icon":"icon-linegongzuotai"}),
                showType:"URL",
                name:title,
                title,
                parentId:obj.appId,
                appId:obj.appId,
                parentKey:obj.key
            }
        },

        setNotHomeAppsByMenu(menu){
            let oldMenu = this.menus.find(item=>item.id === menu.id);
            oldMenu.haveHomePage = menu.haveHomePage;
            oldMenu.children = menu.children;
        },
        setHasBack(hasBack_){
            this.hasBack= hasBack_ ;
        },
        /**
         * 构建路由
         * @returns {Promise<any>}
         * @constructor
         */
        generateRoutes() {
            return new Promise((resolve,reject) => {
                ResourceApi.getFrontApps().then(data=>{
                    this.setLogined(true);
                    if(data){
                        this.setHasBack(data.hasBack);
                        this.setMenus(data.appDtos.sort((a,b)=>a.sn-b.sn));
                        userUser().setUser(data.currentUser);
                        resolve()
                    }
                }).catch((err)=>{
                    reject(err)
                })
            })
        },
        /**
         * 根据appId获取应用对象
         * @param appId
         * @returns {*}
         */
        getAppById(appId){
            return this.currentApps.find(item=>item.appId === appId);
        }
    },
    persist: {
        enabled: true,
        key: USE_MAIN,
        storage: window.sessionStorage,
        pick: [
            'appKey', 'curApp','navigations',
            'navigation','selectedMenuKey','openMenuKeys',
            'buttons','allButtons'
        ]
    }
})




